<template>
  <el-dialog
      :title="mode === 'create' ? '新增城市' : '编辑城市'"
      v-model="visible"
      width="600px"
      @close="handleClose">
    <el-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        label-width="100px">
      <el-form-item label="城市编码" prop="cityCode">
        <el-input
            v-model="formData.cityCode"
            placeholder="请输入城市编码"
            :disabled="mode === 'edit'" />
      </el-form-item>
      <el-form-item label="城市名称" prop="cityName">
        <el-input v-model="formData.cityName" placeholder="请输入城市名称" />
      </el-form-item>
      <el-form-item label="所属省份" prop="province">
        <el-input v-model="formData.province" placeholder="请输入所属省份" />
      </el-form-item>
      <el-form-item label="医药公司数" prop="pharmaCompanyCount">
        <el-input-number
            v-model="formData.pharmaCompanyCount"
            :min="0"
            controls-position="right" />
      </el-form-item>
      <el-form-item label="销售点数量" prop="salesSiteCount">
        <el-input-number
            v-model="formData.salesSiteCount"
            :min="0"
            controls-position="right" />
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="submitForm">确认</el-button>
    </template>
  </el-dialog>
</template>

<script>
import { ref, reactive, watch } from 'vue'
import cityApi from './api/city'

export default {
  props: {
    visible: Boolean,
    mode: {
      type: String,
      default: 'create'
    },
    data: Object
  },
  emits: ['success', 'close'],
  setup(props, { emit }) {
    const formRef = ref(null)
    const formData = reactive({
      cityCode: '',
      cityName: '',
      province: '',
      pharmaCompanyCount: 0,
      salesSiteCount: 0
    })

    // 表单验证规则
    const rules = {
      cityCode: [
        { required: true, message: '请输入城市编码', trigger: 'blur' },
        { pattern: /^[0-9]{6}$/, message: '编码必须为6位数字', trigger: 'blur' }
      ],
      cityName: [
        { required: true, message: '请输入城市名称', trigger: 'blur' }
      ],
      province: [
        { required: true, message: '请输入所属省份', trigger: 'blur' }
      ]
    }

    // 监听传入的数据
    watch(() => props.data, (val) => {
      if (val) {
        Object.keys(formData).forEach(key => {
          formData[key] = val[key]
        })
      } else {
        resetForm()
      }
    }, { immediate: true })

    // 重置表单
    const resetForm = () => {
      Object.keys(formData).forEach(key => {
        if (key === 'pharmaCompanyCount' || key === 'salesSiteCount') {
          formData[key] = 0
        } else {
          formData[key] = ''
        }
      })
    }

    // 提交表单
    const submitForm = async () => {
      try {
        await formRef.value.validate()

        if (props.mode === 'create') {
          await cityApi.addCity(formData)
        } else {
          await cityApi.updateCity(formData)
        }

        emit('success')
        emit('close')
        ElMessage.success('操作成功')
      } catch (e) {
        console.error('表单验证失败', e)
      }
    }

    // 关闭对话框
    const handleClose = () => {
      emit('close')
    }

    return {
      formRef,
      formData,
      rules,
      submitForm,
      handleClose
    }
  }
}
</script>